<template>
  <div>
    <textarea ref="textarea"></textarea>
  </div>
</template>

<script>
import tinymce from "tinymce/tinymce";
import Editor from "@tinymce/tinymce-vue";
import "tinymce/skins/ui/oxide/skin";
import "tinymce/themes/silver/theme";
import "tinymce/icons/default/icons";
import "tinymce/models/dom/model";
import "tinymce/plugins/advlist";
import "tinymce/plugins/autolink";
import "tinymce/plugins/autosave";
import "tinymce/plugins/code";
import "tinymce/plugins/directionality";
import "tinymce/plugins/fullscreen";
import "tinymce/plugins/insertdatetime";
import "tinymce/plugins/link";
import "tinymce/plugins/anchor";
import "tinymce/plugins/lists";
import "tinymce/plugins/media";
import "tinymce/plugins/nonbreaking";
import "tinymce/plugins/pagebreak";
import "tinymce/plugins/preview";
import "tinymce/plugins/searchreplace";
import "tinymce/plugins/table";
import "tinymce/plugins/visualblocks";
import "tinymce/plugins/visualchars";
import "tinymce/plugins/wordcount";
import "tinymce/plugins/image";
import "tinymce/plugins/charmap";
import "tinymce/plugins/autoresize";
import "tinymce/plugins/codesample";
import "tinymce/plugins/directionality";
import "tinymce/plugins/importcss"; // 引入 imagetools 插件脚本
import "./langs/zh_CN.js"; //从官网下载语言包，放在当前文件同级目录下
import { consPage } from "@/api/journalism/journalism";
import { getToken } from "@/utils/auth";

export default {
  components: {},
  props: {
    value: String,
  },
  data() {
    return {
      editor: null,
      uploadUrl: process.env.VUE_APP_BASE_API + "/common/upload", // 上传的图片服务器地址
      headers: {
        Authorization: "Bearer " + getToken(),
      },
    };
  },
  watch: {
    value: {
      handler() {
        this.setValue(this.value);
      },
      immediate: true,
    },
  },
  mounted() {
    tinymce
      .init({
        target: this.$refs.textarea,
        ui_mode: "split",
        language: "zh_CN",
        plugins:
          "lists link icons anchor code wordcount image autoresize  charmap codesample  importcss table visualchars visualblocks searchreplace preview pagebreak nonbreaking media uploadVideo insertdatetime fullscreen directionality autosave autolink advlist",

        toolbar: [
          "undo redo removeformat | bold italic underline strikethrough superscript subscript backcolor forecolor | numlist bullist | blocks | searchreplace fullscreen",
          "fontfamily fontsize fontsizeselect fontsizeinput | alignleft aligncenter alignright alignjustify lineheight outdent indent | link unlink image media icons codesample uploadVideo | preview code",
        ],
        resVideo: "", //上传视频的url
        // uploaded: true, //有没有上传完成
        file_picker_types: "file image media",
        file_picker_callback: (callback, value, meta) => {
          if (meta.filetype === "media") {
            // 创建一个隐藏的文件输入元素
            let input = document.createElement("input");
            input.setAttribute("type", "file");
            input.setAttribute("accept", ".mp4,.mov,.avi,.webm"); // 可接受的视频格式
            input.onchange = function () {
              let file = this.files[0]; // 获取选中的文件
              let formData = new FormData();
              formData.append("file", file);
              // 发送文件到服务器
              fetch(process.env.VUE_APP_BASE_API + "/common/upload", {
                method: "POST",
                body: formData,
                headers: {
                  Authorization: "Bearer " + getToken(),
                },
              })
                .then((response) => response.json())
                .then((data) => {
                  if (data.success) {
                    // 假设服务器返回的视频URL
                    let videoUrl = data.url;
                    callback(videoUrl, { title: file.name }); // 将视频URL传递给tinymce
                  } else {
                    console.error("视频上传失败", data.message);
                  }
                });
            };

            // 触发文件输入元素的点击事件
            input.click();
          }
        },
        content_style: `img { max-width: 100%; /* 设置图片最大宽度为100% */ height: auto; /* 确保图片保持横纵比 */ }`,
        media_live_embed_api_base_url: "", // YouTube API URL
        media_poster_width: 640, // 视频海报宽度
        media_poster_height: 480, // 视频海报高度
        media_default_width: 640, // 默认视频宽度
        media_default_height: 480, // 默认视频高度
        media_dimensions: [640, 480], // 推荐的视频尺寸
        media_dimensions_label: "640x480", // 推荐尺寸的标签
        font_size_formats:
          "9px 10px 11px 12px 14px 16px 18px 20px 22px 24px 26px 28px 36px 42px 48px 72px",
        font_size_input_default_unit: "px",
        images_upload_handler: (blobInfo, progress) =>
          new Promise((resolve, reject) => {
            const xhr = new XMLHttpRequest();
            xhr.withCredentials = false;
            xhr.open("POST", process.env.VUE_APP_BASE_API + "/common/upload");
            xhr.setRequestHeader("Authorization", getToken());
            xhr.upload.onprogress = (e) => {
              progress((e.loaded / e.total) * 100);
            };

            xhr.onload = () => {
              if (xhr.status === 403) {
                reject({ message: "HTTP Error: " + xhr.status, remove: true });
                return;
              }

              if (xhr.status < 200 || xhr.status >= 300) {
                reject("HTTP Error: " + xhr.status);
                return;
              }

              const json = JSON.parse(xhr.responseText);
              if (!json || typeof json.fileName != "string") {
                reject("Invalid JSON: " + xhr.responseText);
                return;
              }

              resolve(json.fileName);
            };

            xhr.onerror = () => {
              reject(
                "Image upload failed due to a XHR Transport error. Code: " +
                  xhr.status
              );
            };

            const formData = new FormData();
            formData.append("file", blobInfo.blob(), blobInfo.filename());

            xhr.send(formData);
          }),
        height: 500,
        promotion: false,
      })
      .then(([editor]) => {
        this.editor = editor;
        this.setValue(this.value);
        editor.on("change keyup undo redo", () => {
          this.$emit("input", editor.getContent());
        });
      });
  },
  beforeDestroy() {
    this.editor?.destroy();
  },
  methods: {
    setValue(val) {
      const oldValue = this.editor?.getContent();
      if (typeof val === "string" && val !== oldValue) {
        this.editor?.setContent(val);
      }
    },
  },
};
</script>

<style>
.tox-tinymce-aux {
  z-index: 10000 !important;
}

.tox .tox-number-input .tox-input-wrapper {
  display: none !important;
}

.tox-statusbar__branding {
  display: none !important;
}
</style>
